package org.nidy.programexercise.ThreadExercise;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadSalesTicket extends Thread {
    static int ticket = 0;
    public void run() {
        while(true){
            if(synchronizedSale()) break;
//            if(lockSale()) break;
        }

    }
    //同步代码块方式实现
    private synchronized boolean synchronizedSale() {
       if(ticket<100){
           try {
               Thread.sleep(100);
           } catch (InterruptedException e) {
               throw new RuntimeException(e);
           }
           ticket++;
           System.out.println(Thread.currentThread().getName()+"正在出售第"+ticket+"张票");
       }else{
           return true;
       }
       return false;
    }
    //锁对象方式实现
    static Lock lock =new ReentrantLock();
    private boolean lockSale() {
        lock.lock();
        try {
            if(ticket<100){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                ticket++;
                System.out.println(Thread.currentThread().getName()+"正在出售第"+ticket+"张票");
            }else{
                return true;
            }
            return false;
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
